package com.example.testble;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.os.ParcelUuid;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class BleGattClient {

    private static final String TAG = BleGattClient.class.getSimpleName();
    ;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothLeScanner scanner;
    private final Set<String> addedServiceIds = new HashSet<>(); // 通过UDP传输过来的iOS的Gatt Server ServiceID集合
    private final Map<String, String> macAndServiceIdMap = new HashMap<>(); // 已经通过配对连接之后的iOS蓝牙地址和对应的Gatt Server ServiceID映射关系

    private BleGattClient() {
        initializeScanner();
    }

    private void initializeScanner() {
        BLogger.w(TAG, "Initializing BleGattClient");
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            BLogger.w(TAG, "Device does not support Bluetooth");
        } else {
            scanner = bluetoothAdapter.getBluetoothLeScanner();
            BLogger.w(TAG, "Bluetooth adapter initialized successfully");
        }
    }

    private static class SingletonHolder {
        private static final BleGattClient INSTANCE = new BleGattClient();
    }

    public static BleGattClient getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void handleServiceId(String serviceId) {
        if (addedServiceIds.contains(serviceId)) {
            return;
        }
        addedServiceIds.add(serviceId);
        startScan();
    }

    @SuppressLint("MissingPermission")
    public void startScan() {
        BLogger.w(TAG, "Starting BLE scan...");
        List<ScanFilter> filters = new ArrayList<>();
        for (String serviceId : addedServiceIds) {
            UUID serviceUUID = UUID.fromString(serviceId);
            filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(serviceUUID)).build());
        }

        ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();

        if (scanner != null) {
            scanner.stopScan(scanCallback);
            scanner.startScan(filters, settings, scanCallback);
            BLogger.w(TAG, "Scan started with service UUID filters: " + addedServiceIds);
        } else {
            BLogger.w(TAG, "Scanner is null, unable to start scan");
        }
    }

    @SuppressLint("MissingPermission")
    private final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            if (macAndServiceIdMap.containsKey(device.getAddress())) {
                return;
            }
            BLogger.w(TAG, "onScanResult callbackType: " + callbackType + " result: " + result);
            BLogger.w(TAG, "Discovered device: " + device.getName() + " (" + device.getAddress() + ")");

            // TODO 根据地址去验证checkBtMacIsPaired,
            boolean checkBtMacIsPaired = true;

            if (checkBtMacIsPaired) {
                if (result.getScanRecord() != null && result.getScanRecord().getServiceUuids() != null) {
                    macAndServiceIdMap.put(device.getAddress(), result.getScanRecord().getServiceUuids().get(0).toString());
                }
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            BLogger.w(TAG, "Scan failed with error code: " + errorCode);
        }
    };
}
